package com.app.internationaltravel.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName AliOssUtil
 * @Description 阿里云对象存储OSS工具类
 * @Author LiHao
 * @Date 2022/12/2 22:21
 * @Version 1.0
 */
public class AliOssUtil {
    //填写Bucket所在地域对应的Endpoint。
    public static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    /** 下面的密钥不能泄漏 */
    private static String accessKeyId = "LTAI5t8nxGLqoknn9xkukWuW";
    private static String accessKeySecret = "1ZQyW7XX1L4DFZ4KgzrgviTrZlAuNi";
    public static String bucket = "mymdstoragespace";
    private static OSS client;

    static {
        client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上传资源
     */
    public static String upload(byte[] data, String objname, Date date) {
        //实现文件上传
        client.putObject(bucket, objname, new ByteArrayInputStream(data));
        return createUrl(objname, date);
    }

    /**
     * 生成访问路径
     */
    public static String createUrl(String objName, Date date) {
        return client.generatePresignedUrl(bucket, objName, date).toString();
    }

    /**
     * 列出存储空间的文件信息
     */
    public static List<String> list() {
        ObjectListing objectListing = client.listObjects(bucket);
        List<String> list = new ArrayList<>();
        // objectListing.getObjectSummaries获取所有文件的描述信息。
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            list.add(objectSummary.getKey());
        }
        return list;
    }

    /**
     * 删除文件
     */
    public static void del(String objName) {
        client.deleteObject(bucket, objName);
    }

}
